import requests
import json
import pandas as pd
import datetime

from utils.write_to_excel import write_to_excel
import aiohttp
import asyncio
from utils.utils import convert_json_data

from utils.question_format import parse_formatted_output

USER_ID = "abc-123"
# 千文32模型解题
# API_KEY = 'app-roa2m5rs5ihVUWtqBWIgkURf'

# deepseek蒸馏模型批改作业
# API_KEY = "app-obaHLVolNEeavXQSJJDLG828"
# FILE_NAME = "assistant-review-distill.xlsx"

# Qwen2.5-32B 千问
# API_KEY = 'app-p5Cu1Uph8fgnh8Rkx6vuePTq'
# FILE_NAME = 'assistant-review-Qwen2.5-32B.xlsx'

# QwQ-7B-instruct
API_KEY = 'app-HDDTWbKCGGPF8nJySDk6bV8C'
FILE_NAME = 'assistant-review-QwQ-instruct-AWQ.xlsx'

# id表示问题唯一   index是同一个问题第几个分数


async def send_chat_request(id, session, query, index, hander=None):
    request_time = datetime.datetime.now().timestamp()  # 获取当前时间
    # 定义请求的URL
    url = "http://8.136.111.93:8008/v1/chat-messages"
    # 定义请求头
    headers = {
        "Authorization": f"Bearer {API_KEY}",  # 使用宏定义的 API_KEY
        "Content-Type": "application/json",
    }

    # 定义请求数据
    data = {
        "inputs": {},
        "query": query,
        "response_mode": "blocking",
        "conversation_id": "",
        "user": USER_ID,  # 使用宏定义的 USER_ID
        "files": [],
    }

    # 发送POST请求
    try:
        async with session.post(
            url, headers=headers, data=json.dumps(data)
        ) as response:
            # 检查响应状态码
            if response.status == 200:
                print("请求成功，返回的数据：")
                response_data = await response.json()
                response_time = datetime.datetime.now().timestamp()  # 获取当前时间
                duration_time = round(response_time - request_time, 2)
                # 将 answer 单独赋值给新的变量
                answer = response_data.get("answer")
                # 解析 answer 变量（假设 answer 是一个 JSON 字符串）
                if isinstance(answer, str):
                    try:
                        parsed_answer = convert_json_data(answer)

                        if callable(hander):
                            parsed_answer = hander(parsed_answer, url)
                        row = parse_formatted_output(query)

                        parsed_answer[f"f分数{index}"] = parsed_answer["score"]
                        del parsed_answer["score"]

                        parsed_answer["duration_time"] = duration_time
                        parsed_answer["id"] = id + 1
                        parsed_answer.update(row)
                        # 解构 question 和 answer 字段
                        question = parsed_answer.get("question")
                        answer_content = parsed_answer.get("answer")
                        write_to_excel(FILE_NAME, parsed_answer)
                        return answer_content

                    except json.JSONDecodeError as e:
                        print("解析 answer 时出错:", e)
                        print("解析 answer 时出错字符串:", answer)
                else:
                    print("answer 不是一个有效的 JSON 字符串。")

            else:
                print(f"请求失败: {response.status}, 响应内容: {await response.text()}")
                return None

            if response.status == 400:
                error_info = await response.json()
                print(
                    f"错误代码: {error_info.get('code')}, 错误信息: {error_info.get('message')}")

    except aiohttp.ClientError as e:
        print(f"请求异常: {e}")
        return None  # 返回 None 以指示请求异常


async def fetch_all_review(querys, hander=None):
    async with aiohttp.ClientSession() as session:  # 创建异步会话
        responses = []  # 存储所有的响应
        for id, query in enumerate(querys):
            print(f"id:{id}")
            tasks = []  # 存储当前组的请求任务
            # 使用 enumerate 获取原始索引
            for index in range(5):
                tasks.append(
                    send_chat_request(id, session, query, index, hander)
                )  # 添加异步请求任务
            group_responses = await asyncio.gather(*tasks)  # 等待当前组的所有请求完成
            responses.extend(group_responses)  # 将当前组的响应添加到总响应列表
        return responses  # 返回所有响应
